package com.moli.iov.manager.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.cache.RedisUtil;
import com.moli.iov.manager.ManagerConstant;
import com.moli.iov.manager.mapper.AuthorityRoleMapper;
import com.moli.iov.manager.model.bo.RoleAuthsBo;
import com.moli.iov.manager.model.dto.AuthorityRoleQueryDto;
import com.moli.iov.manager.model.dto.DictDataQueryByTypeDto;
import com.moli.iov.manager.model.po.*;
import com.moli.iov.manager.service.*;
import com.moli.iov.rest.GenericCode;
import com.moli.iov.rest.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author fudaohui
 * @since 2018-12-12
 */
@Service("iAuthorityRoleService")
@Slf4j
public class AuthorityRoleServiceImpl extends ServiceImpl<AuthorityRoleMapper, AuthorityRole> implements IAuthorityRoleService {

    @Autowired
    private AuthorityRoleMapper authorityRoleMapper;

    @Autowired
    private IAuthorityRoleAuthService iAuthorityRoleAuthService;

    @Autowired
    private IAuthorityAuthService iAuthorityAuthService;
    @Autowired
    private IDictDataService iDictDataService;
    @Autowired
    private IAuthorityRoleService iAuthorityRoleService;

    @Autowired
    private IAuthoritySysUserService iAuthoritySysUserService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public RestResponse saveOrUpdateRole(AuthorityRole authorityRole) {
        if (authorityRole == null) {
            return RestResponse.failure("参数为空!");
        }
        List<Long> allAuths = authorityRole.getAllSelectauths();
        List<Long> halfAuths = authorityRole.getHalfSelectauths();
        if ((allAuths == null && halfAuths == null) || (allAuths.size() <= 0 && halfAuths.size() <= 0)) {
            return RestResponse.failure("参数为空!");
        }
        Long oldRoleId = authorityRole.getId();
        saveOrUpdate(authorityRole);
        Long roleId = authorityRole.getId();
        List<AuthorityRoleAuth> authorityRoleAuths = new ArrayList<>();
        if (allAuths != null && allAuths.size() > 0) {

            for (Long authId : allAuths) {
                AuthorityRoleAuth authorityRoleAuth = new AuthorityRoleAuth();
                authorityRoleAuth.setRoleId(roleId);
                authorityRoleAuth.setAuthId(authId);
                authorityRoleAuth.setSelectStatus(1);
                authorityRoleAuths.add(authorityRoleAuth);
            }
        }
        if (halfAuths != null && halfAuths.size() > 0) {

            for (Long authId : halfAuths) {
                AuthorityRoleAuth authorityRoleAuth = new AuthorityRoleAuth();
                authorityRoleAuth.setRoleId(roleId);
                authorityRoleAuth.setAuthId(authId);
                authorityRoleAuth.setSelectStatus(2);
                authorityRoleAuths.add(authorityRoleAuth);
            }
        }
        if (oldRoleId != null) { //修改角色
            //删除以前关联的角色
            iAuthorityRoleAuthService.deleteAuthorityRoleBatchByroleds(oldRoleId);
            //修改角色要求关联此角色的所有用户都退出登陆
            iAuthoritySysUserService.clearUserAuthCacheByRoleId(oldRoleId);
        }

        //修改角色后，此角色管理的用户全部清空缓存中的权限标记
        iAuthorityRoleAuthService.saveOrUpdateAuthorityRoleAuths(authorityRoleAuths);
        return RestResponse.success();
    }

    @Override
    public RestResponse queryRoleById(long id) {

        QueryWrapper<AuthorityRole> wrapper = new QueryWrapper<>();
        wrapper.select("id,name,type,status,is_delete").eq("id", id);
        AuthorityRole authorityRole = authorityRoleMapper.selectOne(wrapper);
        if (authorityRole == null) {
            return RestResponse.failure("查询失败，该角色不存在");
        }
//        DictDataQueryByTypeDto dictDataQueryByTypeDto = new DictDataQueryByTypeDto();
//        dictDataQueryByTypeDto.setDictType("JSLX");
//        RestResponse<Map<String, String>> mapRestResponse = iDictDataService.queryMapByType(dictDataQueryByTypeDto);
//        if (mapRestResponse == null || mapRestResponse.getCode() == GenericCode.ERROR.getCode()) {
//            return RestResponse.failure("查询失败，字典服务异常");
//        }
//        String type = authorityRole.getType() + "";
//        Map<String, String> stringMap = mapRestResponse.getData();
//        String roleType;
//        if (stringMap == null || (roleType = stringMap.get(type)) == null) {
//            return RestResponse.failure("查询失败，字典服务异常");
//        }
//        authorityRole.setRoleType(roleType);
        if (authorityRole.getStatus() == 0) {
            authorityRole.setUseStatus("启用");
        } else {
            authorityRole.setUseStatus("停用");
        }
        List<Long> allauths = iAuthorityRoleAuthService.queryAuthIdsByRoleId(id, 1);
        authorityRole.setAllSelectauths(allauths);
        List<Long> halfAuths = iAuthorityRoleAuthService.queryAuthIdsByRoleId(id, 2);
        authorityRole.setHalfSelectauths(halfAuths);
        return RestResponse.success(authorityRole);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public RestResponse deleteRoleById(AuthorityRole authorityRole) {
        if (authorityRole == null || authorityRole.getId() == null) {
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }
        RestResponse restResponse = iAuthorityRoleService.queryRoleById(authorityRole.getId());
        AuthorityRole authorityRole1;
        if (restResponse == null || (authorityRole1 = (AuthorityRole) restResponse.getData()) == null) {
            log.error("删除失败，角色不存在");
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }
        if (authorityRole1.getStatus() != 1) {
            log.error("删除失败，只有停用的角色才能被删除");
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }
        Long roleId = authorityRole.getId();
        authorityRole.setIsDelete(1);
        updateById(authorityRole);
        AuthorityRoleAuth authorityRoleAuth = new AuthorityRoleAuth();
        authorityRoleAuth.setIsDelete(1);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_id", roleId);
        iAuthorityRoleAuthService.update(authorityRoleAuth, wrapper);
        return RestResponse.success(ManagerConstant.DELETE_SUCCESS_MSG,null);
    }

    @Override
    public IPage<AuthorityRole> queryRoleByPage(AuthorityRoleQueryDto authorityRoleQueryDto) {
        if (authorityRoleQueryDto == null) {
            return new Page<AuthorityRole>();
        }
        QueryWrapper<AuthorityRole> queryWrapper = new QueryWrapper<AuthorityRole>();
        if (StringUtils.isNotBlank(authorityRoleQueryDto.getName())) {
            queryWrapper.like("name", authorityRoleQueryDto.getName());
        }
//        if (authorityRoleQueryDto.getType() != null) {
//            queryWrapper.eq("type", authorityRoleQueryDto.getType());
//        }
        if (authorityRoleQueryDto.getStatus() != null) {
            queryWrapper.eq("status", authorityRoleQueryDto.getStatus());
        }
        queryWrapper.eq("type", 0);
        //只查询未删除的角色信息
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("gmt_create");
        IPage<AuthorityRole> page = this.page(new Page<AuthorityRole>(authorityRoleQueryDto.getPageNum(), authorityRoleQueryDto.getPageSize()), queryWrapper);
        List<AuthorityRole> records = page.getRecords();
        if (records == null || records.size() <= 0) {
            return new Page<AuthorityRole>();
        } else {

//            DictDataQueryByTypeDto dictDataQueryByTypeDto = new DictDataQueryByTypeDto();
//            dictDataQueryByTypeDto.setDictType("JSLX");
//            RestResponse<Map<String, String>> mapRestResponse = iDictDataService.queryMapByType(dictDataQueryByTypeDto);
//            if (mapRestResponse == null || mapRestResponse.getCode() == GenericCode.ERROR.getCode()) {
//                return new Page<AuthorityRole>();
//            }
//            Map<String, String> stringMap = mapRestResponse.getData();
            for (AuthorityRole record : records) {
                String type = record.getType() + "";
                if (record.getStatus() == 0) {
                    record.setUseStatus("启用");
                } else {
                    record.setUseStatus("停用");
                }
            }
            return page;
        }
    }

//    @Override
//    public RoleAuthsBo queryAuthsByRoleId(long roleId, int isMemu) {
//        RoleAuthsBo roleAuthsBo = new RoleAuthsBo();
//        List<AuthorityAuth> authorityAuths = iAuthorityAuthService.queryAuthTreeByRoleId(roleId, isMemu);
//        roleAuthsBo.setAllAuths(authorityAuths);
//        List<AuthorityRoleAuth> authIds = iAuthorityRoleAuthService.queryAuthIdsByRoleId(roleId);
//        roleAuthsBo.setCheckedAuths(authIds);
//        return roleAuthsBo;
//    }

    @Override
    public AuthorityRole queryRoleByname(AuthorityRole authorityRole) {
        if (authorityRole == null) {
            return null;
        }
        QueryWrapper<AuthorityRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", authorityRole.getName());
        queryWrapper.eq("is_delete", 0);
        return getOne(queryWrapper);
    }

    @Override
    public List<AuthorityRole> listDefalutRoles() {

        List<AuthorityRole> authorityRoles = authorityRoleMapper.listDefalutRoles();
        if (authorityRoles != null && authorityRoles.size() > 0) {
            for (AuthorityRole authorityRole : authorityRoles) {
                Long id = authorityRole.getId();
                List<Long> allauths = iAuthorityRoleAuthService.queryAuthIdsByRoleId(id, 1);
                authorityRole.setAllSelectauths(allauths);
                List<Long> halfAuths = iAuthorityRoleAuthService.queryAuthIdsByRoleId(id, 2);
                authorityRole.setHalfSelectauths(halfAuths);
            }
        }
        return authorityRoles;
    }

    @Override
    public List<AuthorityRole> listRoles() {
        QueryWrapper<AuthorityRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,name,description,status,operator_decription");
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq("status", 0);
        queryWrapper.notIn("id", 1);
        queryWrapper.orderByDesc("gmt_create");
        return list(queryWrapper);
    }


}
